package com.server;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.db.DB;
import com.tools.Constants;
import com.tools.Files;

/**
 * @author lemonjesnme
 * @category user update the stuff image,save the stuff image. if just the
 *           _id,return the user image path.
 */
public class C2S4saveandreturnImage extends HttpServlet {

	@Override
	public void init() throws ServletException {
		Constants.init();
		System.out.println("DB name:" + Constants.DBNAME);
		DB.connDB();
		super.init();
	}

	private static final long serialVersionUID = 1L;
	private HashMap<String, String> friendsParam = new HashMap<String, String>();

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		Enumeration<String> er = request.getParameterNames();
		System.out.println("[vswb4] whitebox4 post begin");
		PrintWriter writer = response.getWriter();
		String user_id = null;
		String value = null;
		String imgPath = null;
		String imgfromS = null;
		while (er.hasMoreElements()) {
			String element = er.nextElement();

			/**
			 * if the user have method to take a image,save the image to sever
			 * files, save file path is project work path. and return the image
			 * address to user.
			 */

			/**
			 * if his friends to look at a image,return the currect friends
			 * image path.
			 */
			if (element.equals("imgfromS")) {
				imgfromS = request.getParameterValues("imgfromS")[0];
				System.out.println("imgfromS:" + imgfromS);
			}

			if (element.equals("user_id")) {
				user_id = request.getParameterValues("user_id")[0];
				imgPath = "http://" + Constants.SERVER_ADDRESS + Constants.PORT + "/tom/res/img/" + user_id + ".jpg";
				// ResultSet rs =
				// DB.select("select img_path from userinfo where user_id='"+user_id+"';");
				// while(rs.next()){
				// imgPath = rs.getString("img_path");
				// }
				writer.println(imgPath);
				System.out.println("[vswb4] user_id:" + user_id);
			}

			if (element.equals("image")) {
				value = request.getParameterValues("image")[0];
				System.out.println("[vswb4] image:" + value);
				InputStream is = request.getInputStream();

				if (is != null) {
					if (Files.createFileDir(Constants.tomcatSrcPath)) {
						File dest = new File(Constants.tomcatSrcPath + user_id + ".jpg");
						if (dest.exists()) {
							dest.delete();
							if (Files.saveFile(is, Constants.tomcatSrcPath + user_id + ".jpg")) {
								DB.update("update userinfo set img_path='" + imgPath + "' where user_id='" + user_id + "';");
								DB.update("update userinfo set time=now() where user_id='" + user_id + "';");
							}
						} else {
							if (Files.saveFile(is, Constants.tomcatSrcPath + user_id + ".jpg")) {
								// friendsParam.put("img_path", imgPath);
								DB.update("update userinfo set img_path='" + imgPath + "' where user_id='" + user_id + "';");
								DB.update("update userinfo set time=now() where user_id='" + user_id + "';");
								friendsParam.clear();
								System.out.println(imgPath);
							}
						}
					}
				}
			}

		}

		if ((imgfromS != null)) {
			String filename = null, formname = "";
			FileOutputStream fout = null;
			HashMap<String, HashSet<Object>> paraMap = new HashMap<String, HashSet<Object>>();
			request.setAttribute("_param", paraMap);
			try {
				ServletInputStream in = request.getInputStream();
				byte b[] = new byte[512], lastByteArray[] = new byte[512];
				String separator;
				int hasRead = 0, offset = 0;
				if ((hasRead = in.readLine(b, 0, b.length)) != -1) {// 判断有没有上传文件
					separator = new String(b, 0, hasRead, "ascii");
					finish: while (true) {
						hasRead = in.readLine(b, 0, b.length);
						
						for (String tmp : new String(b, 0, hasRead, "UTF8").split(";")) {
							if (tmp.trim().toLowerCase().startsWith("filename=")) {
								filename = tmp.substring(tmp.indexOf('"') + 1, tmp.lastIndexOf('"'));
								System.out.println("filename:" + filename);
							} else if (tmp.trim().toLowerCase().startsWith("name=")) {
								formname = tmp.substring(tmp.indexOf('"') + 1, tmp.lastIndexOf('"'));
								System.out.println("formname:" + formname);
							}
						}

						if (filename == null) {// 当传来的一部分不是文件时
							String param = "";
							in.readLine(b, 0, b.length);// 忽略空分割行
							while (true) {
								if ((hasRead = in.readLine(b, 0, b.length)) == -1) {
									response.sendError(400);
									return;
								} else if (separator.equals(new String(b, 0, hasRead, "ascii"))) {
									HashSet hs = paraMap.containsKey(formname) ? paraMap.get(formname) : new HashSet();
									hs.add(param.substring(0, param.length() - 2));// 去掉作为分隔符的"\r\n"
									paraMap.put(formname, hs);
									continue finish;
								} else if (new String(b, 0, hasRead, "ascii").startsWith((separator.substring(0, separator.length() - 2) + "--"))) {
									HashSet hs = paraMap.containsKey(formname) ? paraMap.get(formname) : new HashSet();
									hs.add(param.substring(0, param.length() - 2));// 去掉作为分隔符的"\r\n"
									paraMap.put(formname, hs);
									break finish;
								} else {
									param += new String(b, 0, hasRead, "utf8");
								}
							}
						}// 处理非文件上传结束

						// 以下处理上传文件
						in.readLine(b, 0, b.length);
						in.readLine(b, 0, b.length);// 忽略Content-Type:
						// text/plain这一行和空分割行
						filename = filename.substring(0, filename.lastIndexOf("."));
						System.out.println("S2S filename:"+filename);
						ResultSet rs = DB.select("select _id from user where phone_number='" + filename + "';");
						String user_id1 = null;
						try {
							while (rs.next()) {
								user_id1 = rs.getString("_id");
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						File f = new File(Constants.tomcatSrcPath + user_id1 + ".jpg");
						fout = new FileOutputStream(f);
						while (true) {
							if ((hasRead = in.readLine(b, 0, b.length)) == -1) {
								response.sendError(400);
								return;
							} else if (separator.equals(new String(b, 0, hasRead, "ascii"))) {
								fout.write(lastByteArray, 0, offset - 2);// offset-2==>文件尾，去除request中作为分割用的"\r\n"
								HashSet hs = paraMap.containsKey(formname) ? paraMap.get(formname) : new HashSet();
								hs.add(f);
								paraMap.put(formname, hs);// 将文件的路径存入ParameterMap
								offset = 0;
								fout.close();

								break;
							} else if (new String(b, 0, hasRead, "ascii").startsWith((separator.substring(0, separator.length() - 2) + "--"))) {
								fout.write(lastByteArray, 0, offset - 2);// offset-2==>文件尾，去除request中作为分割符用的"\r\n"
								HashSet hs = paraMap.containsKey(formname) ? paraMap.get(formname) : new HashSet();
								hs.add(f);
								paraMap.put(formname, hs);// 将文件的路径存入ParameterMap
								fout.close();

								break finish;
							} else {
								fout.write(lastByteArray, 0, offset);
								byte tmpB[] = lastByteArray;
								lastByteArray = b;
								b = tmpB;
								offset = hasRead;
							}
						}
						
						// 处理上传文件部分结束
					}
				}
				System.out.println("S2S filename:"+filename);
				ResultSet rs = DB.select("select _id from user where phone_number='" + filename + "';");
				String user_id1 = null;
				try {
					while (rs.next()) {
						user_id1 = rs.getString("_id");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (user_id1 != null) {
					System.out.println("c2s update image ok");
					String imgPath1 = "http://115.238.95.2:8089/tom/res/img/"  +user_id1 + ".jpg";
					System.out.println("img_path1:"+imgPath1);
					DB.update("update userinfo set img_path='" + imgPath1 + "' where user_id='" + user_id1 + "';");
					DB.update("update userinfo set time=now() where user_id='" + user_id1 + "';");
				}
			} catch (NullPointerException npe) {
				response.sendError(400);
			} catch (ArrayIndexOutOfBoundsException aio) {
				response.sendError(400);
			} finally {
				if (fout != null) {
					fout.close();
				}
			}
		}

		/*
		 * String contentType = request.getContentType(); if ((contentType !=
		 * null) && (contentType.indexOf("multipart/form-data") >= 0)) {
		 * DataInputStream in = new DataInputStream(request.getInputStream());
		 * int formDataLength = request.getContentLength(); byte dataBytes[] =
		 * new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0;
		 * while (totalBytesRead < formDataLength) { byteRead =
		 * in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead +=
		 * byteRead; } String file = new String(dataBytes); String saveFile =
		 * file.substring(file.indexOf("filename=\"") + 10); saveFile =
		 * saveFile.substring(0, saveFile.indexOf("\n")); saveFile =
		 * saveFile.substring(saveFile.lastIndexOf("\\")+
		 * 1,saveFile.indexOf("\"")); int lastIndex =
		 * contentType.lastIndexOf("="); String boundary =
		 * contentType.substring(lastIndex + 1,contentType.length()); int pos;
		 * pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1;
		 * pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1;
		 * 
		 * int boundaryLocation = file.indexOf(boundary, pos) - 4;
		 * System.out.println("boundaryLocation:"+boundaryLocation); int
		 * startPos = ((file.substring(0, pos)).getBytes()).length; int endPos =
		 * ((file.substring(0, boundaryLocation)).getBytes()).length;
		 * System.out.println("endPos:"+endPos); saveFile =
		 * Constants.tomcatSrcPath +user_id+".jpg";
		 * System.out.println("saveFile:"+saveFile); FileOutputStream fileOut =
		 * new FileOutputStream(saveFile); fileOut.write(dataBytes, startPos,
		 * (endPos - startPos)); fileOut.flush(); fileOut.close(); } }
		 */

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Enumeration<String> er = request.getParameterNames();
		System.out.println("[vswb4] whitebox4 get begin");
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		String _id = null;
		String imgPath = null;
		while (er.hasMoreElements()) {
			String element = er.nextElement();
			if (element.equals("_id")) {
				_id = request.getParameterValues("_id")[0];
				imgPath = "http://" + Constants.SERVER_ADDRESS + Constants.PORT + "/tom/res/img/" + _id + ".jpg";
				ResultSet rs = DB.select("select img_path from userinfo where user_id='" + _id + "';");
				try {
					while (rs.next()) {
						imgPath = rs.getString("img_path");
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				writer.println(imgPath);
				System.out.println("[vswb4] imgPath:" + imgPath);
			}
		}
	}

}
